package com.jd.fruit.controller.admin.auth;

import java.io.IOException;
import java.util.List;

import com.jd.fruit.common.annotation.Controller;
import com.jd.fruit.common.controller.BaseController;
import com.jd.fruit.common.util.DictUtil;
import com.jd.fruit.common.util.MD5;
import com.jd.fruit.common.util.StringUtil;
import com.jd.fruit.model.admin.auth.AdminUser;
import com.jd.fruit.model.admin.auth.AdminUserRole;
import com.jd.fruit.model.admin.auth.Role;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;

/**
 * 管理员
 * 
 * @author lishunfeng
 * 
 */
@Controller("/admin/auth/user")
public class AdminUserController extends BaseController {
	/**
	 * 添加
	 */
	public void add() {
		List<Role> roleList = Role.dao.list();
		this.setAttr("roleList", roleList);
		this.setAttr("oprtype", DictUtil.oprSave);
		render("user_add.html");
	}

	/**
	 *数据列表
	 */
	public void list() {
		int pageNumber = this.getParaToInt(0,1);
		Page<AdminUser> admins = AdminUser.dao.list(pageNumber,DictUtil.default_pageSize);
		this.setAttr("admins", admins);
		render("user_list.html");
	}

	/**
	 * 编辑
	 */
	public void detail() {
		String id = StringUtil.getDcodePara(getRequest(), "id");
		AdminUser user = AdminUser.dao.findById(id);
		Role currntRole = Role.dao.getRole(user.getStr("id"));
		List<Role> roleList = Role.dao.list();
		this.setAttr("roleList", roleList);
		this.setAttr("adminUser", user);
		this.setAttr("currntRole", currntRole);
		this.setAttr("oprtype", DictUtil.oprUpdate);
		render("user_add.html");// 这个是页面的命名规范
	}

	/**
	 * 删除
	 * 
	 * @throws IOException
	 */
	public void delete() throws IOException {
		String id = StringUtil.getDcodePara(getRequest(), "id");
		boolean isOk = AdminUser.dao.deleteById(id);
		if (isOk) {// 删除成功
			AdminUserRole.dao.delAdminRelationRole("admin_id", id);
			this.renderText(DictUtil.success);
		} else { // 删除失败
			this.renderText(DictUtil.failed);
		}
	}

	/**
	 *保存
	 */
	public void save() {
		AdminUser user = getModel(AdminUser.class);
		AdminUserRole userRole = getModel(AdminUserRole.class);
		// 对密码MD5加密
		String password = user.get("password");
		if (StrKit.notBlank(password)) {
			user.set("password", MD5.md5(password.toString()));
		}
		String oprtyp = this.getPara("oprtype");
		if (oprtyp.equals(DictUtil.oprSave)) {
			String id = AdminUser.dao.save(user);
			userRole.set("admin_id", id);
		} else {
			String updateUserId = user.getStr("id");
			if (updateUserId != null) {
				AdminUserRole.dao
						.delAdminRelationRole("admin_id", updateUserId);
				userRole.set("admin_id", updateUserId);
			}
			user.update();
		}
		// 保存关联数据
		AdminUserRole.dao.save(userRole);
		this.redirect("/admin/auth/user/list");
	}

}
